package Middleware

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"web_back_go/Response"
)

/*
RecoveryMiddleware
@Description: 当有错误panic 时，捕获错误并返回自定义的 JSON 响应
*/

func RecoveryMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				// 发生 panic 时返回自定义的 JSON 响应
				c.JSON(http.StatusOK, Response.ResponseBody{
					Code:    "A00005",
					Data:    nil,
					Success: false,
					Msg:     err.(string),
				})
				c.Abort() // 终止请求处理链
			}
		}()
		c.Next() // 继续处理请求
	}
}
